import { cloneDeep } from "lodash";
import dayjs from "dayjs";

import { yunNao } from "@src/api/yunNao";

import { DomMessageInstance } from "../../utils/DomMessage";
import { DataSourceTypeEnum } from "@src/globalData/enum";
import { getTimePoints } from "@src/utils/common";

export const saveWebSpiderDataV2 = async (saveData:{
  data_item: string;
  data: any[];
  date_time: string;
}) => {
  try {
    const haveData = (saveData?.data || []).some(item =>{
      const objVal = cloneDeep(item)
      delete objVal.sourceIdentity
      delete objVal.runDate
      delete objVal.channel_name
      delete objVal.data_type

      return Object.values(objVal).some(val =>{
        if(typeof val === 'number') return true
        return !!val
      })
    })

    if(!haveData) {
      DomMessageInstance.error({content:'无数据，不存'})
      console.log('无数据，不存')
      return Promise.reject()
    }

    console.log('存储数据：', saveData)
    await yunNao.datapreservationV2(saveData);
    console.log("获取数据存储成功", dayjs().format("YYYY-MM-DD HH:mm:ss"));
  } catch (e) {
    DomMessageInstance.error({content:'获取数据存储失败, 请联系开发人员'})
    console.error("获取数据存储失败: ", e);
    return Promise.reject(e)
  }
}

/**
 * 校验选择框
 * 【信息披露】-【综合查询】-【省间现货】`,
    pageName: '日前通道可用容量'
 */
   const tradingAheadChannelValidate = () => {
    const formList = Array.from((document?.querySelector('iframe')?.contentDocument || document)?.querySelectorAll('.fr-trigger-texteditor') || {length:0})?.map((input:any) => input?.value || '').filter(val => !!val)
    return {
      validateResult: formList?.length === 3, 
      errMsg: '选择框 存在未选'
    }
  }

type DataInfo = {
  statement: string, // 说明
  pageName: string, // 数据项名称
  typeKey: DataSourceTypeEnum | string, // 表名，后端加密
  keys: string[], // 对应列的索引值
  pageValidate?: Function, // 获取数据前的校验方法
  data?: string[], // 获取到dom节点中的表格的二维数组数据
}

/** 综合查询系统中需要手动获取的数据项 */
const getDataInfo:DataInfo[] = [
  /*************************  省间现货  ***********************************************/
  {
    statement: `【信息披露】-【综合查询】-【省间现货】`,
    pageName: '日前通道可用容量',
    // typeKey: 'trading_ahead_channel_cap',
    typeKey: 'aYIKR0dmQLHkzkIFSLsStebVGqNI2p4wr3f9De3EqtA=',
    keys: ['volume', 'channel_name', 'data_type'], // "channel_name": "通道名称"；"data_type": "数据类型",
    pageValidate: tradingAheadChannelValidate
  },
  {
    statement: `【信息披露】-【综合查询】-【省间现货】`,
    pageName: '电力平衡裕度',
    // typeKey: 'trading_power_balance_margin',
    typeKey: 'SL2k5FF8NId76Te6JW5oiGwXuOzv4LHOkc2FT1HidZo=',
    keys: ['level']
  },
  {
    statement: `【信息披露】-【综合查询】-【省间现货】`,
    pageName: '可再生能源富余程度',
    // typeKey: 'trading_renewable_energy_surplus_level',
    typeKey: 'JoMC5QkDO1VTLD02+jGS/Ff3bbCijArgOufFwZr2IWaymJYF8aOZ0eBQqoa0eF1I',
    keys: ['level'],
  }
]

/** 获取dom节点中的数据 */
const getDomTableData = () => {
  const dom = document?.querySelector('iframe')?.contentDocument || document
  return Array.from(dom?.querySelector('.rows-height-counter')?.querySelectorAll?.(`tr:nth-child(even) > td`) || {length:0}).map(td => td?.textContent || '')
}

/** 点击页面中 获取数据 按钮时触发的获取dom中数据的方法 */
export const getCurrentPageInfo = ():Partial<DataInfo> | void | undefined => {
  const _pageName = Array.from(document?.querySelector('.el-col-24')?.querySelectorAll('.el-breadcrumb__inner') || {length:0})?.pop()?.textContent

  if(!_pageName) return DomMessageInstance.error({content:'获取页面信息失败'})
 
  const dataInfo = getDataInfo.find(item => item.pageName === _pageName)
  if(!dataInfo) return DomMessageInstance.error({content:'当前页面未配置获取数据 <br> 或放大窗口再试'})
  if(dataInfo?.pageValidate) {
    const {validateResult = false, errMsg = ''} = dataInfo.pageValidate()
    if(!validateResult) return DomMessageInstance.error({content: errMsg})
  }

  const {statement, pageName} = dataInfo

  const data = getDomTableData()

  if(data?.length !== 96) {
    const message = `获取数据失败! <br> ${statement} <br> ${pageName}`
    return DomMessageInstance.error({content:message})
  }

  return {
    ...dataInfo,
    data
  }
}

/** 数据的统一结构 */
const combineSaveStructure = (data:any[], dataItem:string, date_time = dayjs().format('YYYY-MM-DD HH:mm:ss')) => {
  return {
    data_item: dataItem,
    data,
    date_time
  }
}

/** 处理96点数据 */
const deal96data = (dataInfo:Partial<DataInfo>, formValList:string[]) => {
  const sourceIdentity = import.meta.env.VITE_APP_SOURCE_ID
  const {data, typeKey, keys} = dataInfo as DataInfo

  const pdate = formValList[0]
  if(!pdate) DomMessageInstance.error({content:'获取日期失败'})

  const extraObj:Record<any,any> = {}
  formValList.forEach((val, index) => {
    if(index === 0) return
    extraObj[keys[index]] = val
  })

  const runTime96 = getTimePoints('96_2')

  const dealedData:any[] = [];

  (data || [])?.forEach((val, index) => {
    dealedData.push({
      sourceIdentity,
      // "runDate": "2024-09-26 00:00",
      // "oriRunDate": "2024-09-26 00:15",
      runDate:`${pdate} ${runTime96[index]}`,
      // oriRunDate:`${weekDates[idx]} ${time}`,
      [keys?.[0] as string]: val,
      ...extraObj
    })
  })

  return combineSaveStructure(dealedData, typeKey as string, dayjs(pdate).format('YYYY-MM-DD HH:mm:ss'))
}


/** 处理数据 */
export const dealAllTypeData = (dataInfo:Partial<DataInfo>) => {
  const pdateDomList:any[] = Array.from((document?.querySelector('iframe')?.contentDocument || document)?.querySelectorAll('.fr-trigger-texteditor') || {length:0})
  const formValList:string[] = pdateDomList.map((input:any) => input?.value || '')

  return deal96data(dataInfo, formValList)
}